<template>
  <div class="app-container">
    <el-card class="table-card">
      <div slot="header" class="clearfix">
        <toolbar :config="toolbarConfig" @dialog="showDialog" />
      </div>
      <el-table
        v-el-height-adaptive-table="{bottomOffset: 51}"
        v-loading="tableLoading"
        :data="treeData"
        border
        row-key="id"
        size="mini"
        width="100%"
        height="100px"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column type="selection" align="center" width="55" />
        <el-table-column prop="name" label="权限名称" min-width="30" />
        <el-table-column prop="display_name" align="center" label="显示名称" min-width="20" />
        <el-table-column prop="icon" align="center" label="图标" min-width="10">
          <template slot-scope="{row}">
            <i :class="row.icon" />
          </template>
        </el-table-column>
        <el-table-column prop="sort" align="center" label="排序" min-width="10" />
        <el-table-column prop="icon" align="center" label="菜单" min-width="20">
          <template slot-scope="{row}">
            <el-switch
              v-model="row.is_menu"
              disabled
              size="mini"
              active-color="#13ce66"
              :active-value="1"
              :inactive-value="0"/>
          </template>
        </el-table-column>
        <el-table-column prop="updated_at" align="center" label="更新时间" min-width="30" />
        <el-table-column align="center" label="操作" min-width="30">
          <template slot-scope="{row}">
            <el-button type="text" size="mini" @click="edit(row)">
              编辑
            </el-button>
            <el-button v-if="row.status!=='deleted'" size="mini" type="text" @click="del(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      :title="dialogTitle"
      width="30%"
      :visible.sync="dialogVisible">
      <el-form ref="form" :model="form" :rules="rules" :validate-on-rule-change="false" label-width="90px" size="small">
        <el-form-item label="父级" prop="parent_id">
          <select-tree
            :options="treeData"
            :props="{value:'id', label: 'display_name', children: 'children'}"
            :value="form.parent_id"
            :searchable="false"
            :accordion="true"
            @getValue="getSelectTreeValue"
          />
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="form.name" auto-complete="off" />
        </el-form-item>
        <el-form-item label="显示名称" prop="display_name">
          <el-input v-model="form.display_name" auto-complete="off" />
        </el-form-item>
        <el-form-item label="菜单" prop="is_menu">
          <el-switch
            v-model="form.is_menu"
            active-color="#13ce66"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" type="number" min="0" placeholder="排序从大到小" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="form.icon">
            <el-button slot="append" @click="dialogIconVisible = true">搜索图标</el-button>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="save">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="选择图标"
      width="50%"
      class="icon-dialog"
      :visible.sync="dialogIconVisible">
      <div class="icons-container">
        <el-scrollbar wrap-class="scrollbar-wrapper" style="height: 100%">
          <ul class="icon-list">
            <li v-for="item of elementIcons" :key="item" @click="confirmIcon('el-icon-' + item)">
              <span>
                <i :class="'el-icon-' + item" />
                <span class="icon-name">{{ item }}</span>
              </span>
            </li>
          </ul>
        </el-scrollbar>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Toolbar from '@/components/Toolbar'
import SelectTree from '@/components/SelectTree'
import { getPermissionList, createPermission, updatePermission, destroyPermission } from '@/api/system/permisson'
import elementIcons from './element-icons'
import { sortPermission, array2tree, deepClone } from '@/utils'
import elHeightAdaptiveTable from '@/directive/el-table'

export default {
  components: {
    Toolbar,
    SelectTree
  },
  directives: { elHeightAdaptiveTable },
  filters: {
    statusFilter(status) {
      const statusMap = ['info', 'success']
      return statusMap[status]
    }
  },
  data() {
    return {
      toolbarConfig: [],
      tableLoading: true,
      tableData: [],
      treeData: [],
      elementIcons,
      dialogVisible: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogTitle: '',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'display_name'
      },
      form: {
        parent_id: 0,
        name: '',
        display_name: '',
        is_menu: 1,
        sort: 0,
        icon: ''
      },
      rules: {
        parent_id: [
          { type: 'number', min: 0, message: '请选择正确的父级', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: ['blur', 'change'] },
          { type: 'string', max: 191, message: '名称最大长度为191', trigger: 'blur' }
        ],
        display_name: [
          { required: true, message: '请输入显示名称', trigger: ['blur', 'change'] },
          { type: 'string', max: 191, message: '显示名称最大长度为191', trigger: 'blur' }
        ],
        is_menu: [
          { type: 'enum', message: '请选择正确的菜单项', trigger: 'blur', enum: [0, 1] }
        ],
        sort: [
          { type: 'number', message: '排序请输入数字类型', trigger: 'blur', min: 0 }
        ],
        icon: [
          { type: 'string', max: 50, message: '图标最大长度为50', trigger: 'blur' }
        ]
      },
      dialogIconVisible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      getPermissionList().then(response => {
        const { code, data, message } = response
        if (code === 1) {
          this.tableData = deepClone(data.list)
          this.treeData = array2tree(deepClone(this.tableData))
          this.toolbarConfig = data.permissions
        } else {
          this.$message({
            message: message || 'Error',
            type: 'error'
          })
        }
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    showDialog(event, text, type) {
      if (event === 'add') {
        this.add(text)
      } else if (event === 'del') {
        this.del()
      }
    },
    add(text) {
      this.dialogTitle = text + '权限'
      if (this.$refs['form'] !== undefined) {
        this.$refs.form.resetFields()
      }
      this.$nextTick(() => {
        this.form = {
          parent_id: 0,
          name: '',
          display_name: '',
          is_menu: 1,
          sort: 0,
          icon: ''
        }
      })
      this.dialogVisible = true
    },
    edit(row) {
      this.dialogTitle = '编辑权限'
      this.form = deepClone(row)
      this.dialogVisible = true
    },
    getSelectTreeValue(id) {
      this.form.parent_id = id
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (!this.form.id) {
            createPermission(this.form).then(response => {
              let message_type = 'error'
              const { code, data, message } = response
              if (code === 1) {
                this.tableData.push(data)
                sortPermission(this.tableData)
                this.treeData = array2tree(this.tableData)
                message_type = 'success'
                if (data.is_menu === 1) this.generateSidebar()
              }
              this.$message({
                message: message || 'Error',
                type: message_type
              })
            })
          } else {
            updatePermission(this.form).then(response => {
              let message_type = 'error'
              const { code, data, message } = response
              if (code === 1) {
                const index = this.tableData.findIndex(item => {
                  return item.id === data.id
                })
                this.$set(this.tableData, index, data)
                sortPermission(this.tableData)
                this.treeData = array2tree(deepClone(this.tableData))
                message_type = 'success'
                this.generateSidebar()
              }
              this.$message({
                message: message || 'Error',
                type: message_type
              })
            }).catch(() => {
            })
          }
          this.dialogVisible = false
        } else {
          return false
        }
      })
    },
    del(row) {
      destroyPermission(row).then(response => {
        let message_type = 'error'
        const { code, message } = response
        if (code === 1) {
          const index = this.tableData.findIndex(item => {
            return item.id === row.id
          })
          this.tableData.splice(index, 1)
          sortPermission(this.tableData)
          this.treeData = array2tree(this.tableData)
          message_type = 'success'
          if (row.is_menu === 1) this.generateSidebar()
        }
        this.$message({
          message: message,
          type: message_type
        })
      }).catch(() => {})
    },
    confirmIcon(icon) {
      this.form.icon = icon
      this.dialogIconVisible = false
    },
    generateSidebar() {
      // 存储权限列表
      this.$store.dispatch('permission/setPermissions', this.tableData)
    }
  }
}
</script>

<style lang="scss" scoped>
.icon-dialog {

  ::v-deep .el-dialog__body {
    /*padding: 30px 20px 0 20px!important;*/
  }

  .iconfont {
    font-size: 30px;
  }

  .icons-container {
    overflow: hidden;
    height: 375px;

    .icon-list {
      margin: 10px 0;
      font-size: 14px;
      color: #5e6d82;
      line-height: 2em;
      list-style: none;
      padding: 0!important;
      border: 1px solid #eaeefb;
      border-radius: 4px;
      overflow: auto;

      li {
        float: left;
        width: 16.66%;
        text-align: center;
        height: 120px;
        line-height: 120px;
        color: #666;
        font-size: 13px;
        border-right: 1px solid #eee;
        border-bottom: 1px solid #eee;
        margin-right: -1px;
        margin-bottom: -1px;

        span {
          line-height: normal;
          color: #99a9bf;
          display: inline-block;
          vertical-align: middle;
          margin-top: 0;
        }

        i {
          display: block;
          font-size: 32px;
          margin-bottom: 15px;
          color: #606266;
        }

        .icon-name {
          display: inline-block;
          padding: 0 3px;
          height: 1em;
        }
      }
    }

    .tab-pane-height {
      height: 275px;
      overflow: auto;
    }

    .icon-item {
      margin: 6px;
      height: 85px;
      text-align: center;
      width: 85px;
      float: left;
      font-size: 30px;
      color: #24292e;
      cursor: pointer;
    }

    span {
      display: block;
      font-size: 16px;
      margin-top: 10px;
    }

    .disabled {
      pointer-events: none;
    }

    ::v-deep .el-scrollbar {
      .el-scrollbar__wrap {
        overflow-x: auto;
      }
      .is-vertical {
        right: 0px;
      }
    }

  }
}
</style>
